package fourmiefight.ihm;

import java.awt.Graphics2D;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.dyn4j.collision.Fixture;
import org.dyn4j.dynamics.Body;
import org.dyn4j.dynamics.BodyFixture;
import org.dyn4j.geometry.Convex;
import org.dyn4j.geometry.Polygon;
import org.dyn4j.geometry.Rectangle;
import org.dyn4j.geometry.Vector2;

import fourmiefight.abstractionlib2d.IHMItem;

/**
 * Classe FourmiliereView permet l'affichage de la fourmiliere 
 * @extends DrawableBody
 */
public class FourmiliereView extends IHMItem 
{
	private static final String IMG_PATH = "./Ressources/fourmiliere.png";
	private BufferedImage img = null;

	public FourmiliereView() 
	{
		super();
		
		try 
        {
        	File file = new File(IMG_PATH);
        	img = ImageIO.read(file);
		} 
        catch (Exception e1) 
        {
			e1.printStackTrace();
		}
	}

	@Override
	public void render(Graphics2D g, Body body) 
	{
		AffineTransform ot = g.getTransform();
		
		AffineTransform lt = new AffineTransform();
		lt.translate(body.getTransform().getTranslationX() * SCALE,
				body.getTransform().getTranslationY() * SCALE);
		lt.rotate(body.getTransform().getRotation());

		g.transform(lt);
		for (int i = 0 ; i < body.getFixtureCount() ; i++) 
		{
			Fixture fixture = body.getFixture(i);
			Convex convex = fixture.getShape();
			if (convex instanceof Polygon) 
			{
				Polygon p = (Polygon) convex;
				int l = p.getVertices().length;
				int[] x = new int[l];
				int[] y = new int[l];

				int ii = 0;
				for (Vector2 v : p.getVertices()) 
				{
					x[ii] = (int) ((v.x) * SCALE);
					y[ii] = (int) ((v.y) * SCALE);
					ii++;
				}

				java.awt.Polygon poly = new java.awt.Polygon(x, y, l);
				TexturePaint tPaint = new TexturePaint(img, poly.getBounds2D());
				g.setPaint(tPaint);
				g.fillPolygon(poly);
			}
		}
		g.setTransform(ot);
	}
}